<?php


namespace app\common\business;


use app\common\lib\Str;
use think\Exception;

class User
{
    public $userObj = null;

    public function __construct()
    {
        //初始化模型对象
        $this->userObj = new \app\common\model\mysql\User();
    }

    /**
     * 用户登录
     * @param $data
     * @return array|bool
     * @throws Exception
     */
    public function loginByPhone($data) {
        //获取缓存中的验证码
        $redisCode = cache(config('redis.code_pre').$data['phone_number']);
        if (empty($redisCode) || $redisCode != $data['code']) {
            throw new Exception('验证码不正确', config('status.send_sms_faild'));
        }
        //判断用户是否存在  不存在生成新用户  返回token
        $user = $this->userObj->getUserByPhoneNumber($data['phone_number']);
        if (!$user) {
            $userData = [
                'username' => 'zzihou-' . $data['phone_number'],
                'phone_number' => $data['phone_number'],
                'type'  => $data['type'],
                'status' => 1,
                'last_login_ip'=> request()->ip(),
                'last_login_time'=> time()
            ];

            try {
                $this->userObj->save($userData);
                $userId = $this->userObj->id;
                $username = $this->userObj->username;
            } catch (\Exception $e) {
                throw new Exception('数据库内部异常');
            }

        } else {
            $user = $user->toArray();
            $userId = $user['id'];
            $username= $user['username'];
            //更新
            $updateData = [
                'last_login_ip'=> request()->ip(),
                'last_login_time'=> time()
            ];
            try {
                $this->userObj::update($updateData, ['id'=> $userId]);
            } catch (\Exception $e) {
                throw new Exception('数据库内部异常');
            }
        }
        //生成Token  保存在Redis
        $token = Str::getLoginToken($data['phone_number']);
        $redisData = [
            "id"=> $userId,
            "username"=>$username,
        ];
        $res = cache(config('redis.token_pre').$token, $redisData, config('redis.token_expire'));
        return $res ? ['token'=> $token, 'username'=> $username] : false;
    }

    /**
     * 通过ID返回正常的用户数据
     * @param $id
     * @return array
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function getNormalUserById($id) {
        $user = $this->userObj->getUserById($id);
        if (!$user || $user->status != 1) {
            return [];
        }
        return $user->toArray();
    }

    /**
     * 通过用户名 返回用户数据
     * @param $username
     * @return array
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function getNormalUserByUsername($username) {
        $user = $this->userObj->getUserByUsername($username);
        if (!$user || $user->status != 1) {
            return [];
        }
        return $user->toArray();
    }

    public function update($id, $data) {
        //判断用户是否存在
        $user = $this->getNormalUserById($id);
        if (!$user) {
            throw new Exception(config('status.error'), '该用户不存在');
        }
        //检查用户名是否存在
        $userResult = $this->getNormalUserByUsername($data['username']);
        if ($userResult && $userResult['id'] != $id) {
            throw new Exception('该用户名已存在', config('status.error'));
        }
        //更新数据
        if ($this->userObj->updateById($id, $data)) {
            //修改缓存的用户信息
            //cache(config('redis.token_pre').$token, $redisData, config('redis.token_expire'));
            return true;
        }
        return false;

    }
}